<template>
	<div class="exercises-result" v-loading.fullscreen.lock="loading" element-loading-text="拼命加载中">
		<div class="preview-head">
			<!-- <router-link to="/exercises/task"><i class="el-icon-arrow-left"></i>返回</router-link> -->
			<a @click="goBack()"><i class="el-icon-arrow-left"></i>返回</a>
			<div class="result-submit">
				<el-button type="primary" @click="reviewTest()" plain>保存阅卷</el-button>
				<el-button type="primary" @click="submitTest()">提交并反馈学生</el-button>
			</div>
		</div>
		<div class="preview-conten maxW">
			<div class="preview-conten-l">
				<div class="preview-conten-l-h">
					<h3>{{testObj.name}}</h3>
					<p>考试时间：{{totalTimer ? totalTimer : '--'}} 分钟，满分{{testObj.score}}分</p>
				</div>
				<ul>
					<template v-for="(type, list) of testList.question_type">
						<li class="preview-conten-list" :key="type.id">
							<div class="preview-conten-title">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，共{{type.score}}分<span v-show="type.common">，{{type.common}}。</span>)
							</div>
							<ul class="preview-conten-subject">
								<template v-for="(item, index) of testList.question_list" v-if="parseInt(item.qt_id) == parseInt(type.id)">
									<li class="preview-conten-subject-c" v-if="parseInt(item.type_base_id) === 1 ||  parseInt(item.type_base_id) === 2 || parseInt(item.type_base_id) === 4" :key="item.id">
										<i v-if="answerList.length !=0 && answerList[item.id].score != 0" class="el-icon-check exercises-test-result"></i>
										<i v-else class="el-icon-close exercises-test-result"></i>
										<template>
											<div v-if="item.pattern == 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div v-if="item.pattern == 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong v-if="item.score">({{item.score}}分)</strong>
											</div>
										</template>
										<ul class="preview-topic">
											<template v-if="item.pattern == 1">
												<li class="preview-subject-title option-checked" v-for="(option,index2) of item.option" :key="index2">
													<template v-if="answerList.length !=0 && !in_array( option.name, answerList[item.id].answer ) && item.answer != null && in_array( option.name, item.answer )">
														<el-checkbox class="d" disabled :checked='true' :label="option.name">
														</el-checkbox>
														<div v-if='parseInt(item.type_base_id) !== 4' v-html="option.value"></div>
													</template>
													<template v-else-if="item.answer != null && in_array( option.name, item.answer )">
														<el-checkbox class="a" disabled :checked='true' :label="option.name">
														</el-checkbox>
														<div v-if='parseInt(item.type_base_id) !== 4' v-html="option.value"></div>
													</template>
													<template v-else-if="answerList.length !=0 && answerList[item.id].answer != null && !in_array( option.name, item.answer ) && in_array( option.name, answerList[item.id].answer )">
														<el-checkbox class="b" disabled :checked='true' :label="option.name">
														</el-checkbox>
														<div v-if='parseInt(item.type_base_id) !== 4' v-html="option.value"></div>
													</template>
													<template v-else>
														<el-checkbox class="c" disabled :label="option.name">
														</el-checkbox>
														<div v-if='parseInt(item.type_base_id) !== 4' v-html="option.value"></div>
													</template>
												</li>
											</template>
											<template v-if="item.pattern == 2">
												<li class="preview-subject-title option-checked option-pattern" v-for="(option,index2) of item.option" :key="index2">
													<template v-if="answerList.length !=0 && !in_array( option.name, answerList[item.id].answer ) && item.answer != null && in_array( option.name, item.answer )">
														<el-checkbox class="d" disabled :checked='true' :label="option.name">
														</el-checkbox>
														<!-- <div  v-html="option.value"></div> -->
													</template>
													<template v-else-if="item.answer != null && in_array( option.name, item.answer )">
														<el-checkbox class="a" disabled :checked='true' :label="option.name">
														</el-checkbox>
														<!-- <div v-html="option.value"></div> -->
													</template>
													<template v-else-if="answerList.length !=0 && answerList[item.id].answer != null && !in_array( option.name, item.answer ) && in_array( option.name, answerList[item.id].answer )">
														<el-checkbox class="b" disabled :checked='true' :label="option.name">
														</el-checkbox>
														<!-- <div  v-html="option.value"></div> -->
													</template>
													<template v-else>
														<el-checkbox class="c" disabled :label="option.name">
														</el-checkbox>
														<!-- <div v-html="option.value"></div> -->
													</template>
												</li>
											</template>
										</ul>
										<el-collapse accordion class="preview-answer">
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>得分: {{ answerList.length !=0 ? answerList[item.id].score : 0}} </span>
													</div>
												</template>
												<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>
									<li class="preview-conten-subject-c" v-else :key="item.id">
										<i v-if="answerList.length !=0 && answerList[item.id].score != 0" class="el-icon-check exercises-test-result"></i>
										<i v-else-if="answerList.length !=0 && answerList[item.id].answer == null" class="el-icon-close exercises-test-result"></i>
										<!-- <i v-else-if="answerList[item.id].answer != null && answerList[item.id].score == 0" class="el-icon-close exercises-test-result"></i> -->
										<i v-else class="el-icon-time exercises-test-result"></i>
										<template>
											<div v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong v-if="item.score">({{item.score}}分)</strong>
											</div>
											<div v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
										</template>
										<template>
											<div class="knowledge-answer" v-if="parseInt(item.type_base_id) === 3 ">
												<span>答案</span>
												<template v-if="answerList.length != 0">
													<div class="knowledge-html">
														<div v-for="(answer, num) of answerList[item.id].answer">
															<i>{{++num }}.</i>
															<span v-if="answer.answer"> {{answer.answer}}</span>
															<span v-else class="knowledge-html-un"> 未作答</span>
														</div>
													</div>
												</template>
												<div class="knowledge-html-un" v-else><i class="el-icon-warning-outline"></i>未作答</div>
											</div>
											<div class="knowledge-answer" v-else>
												<span>答案</span>
												<div class="knowledge-html" v-if="answerList[item.id].answer != ''" v-html="answerList[item.id].answer"></div>
												<div class="knowledge-html-un" v-else><i class="el-icon-warning-outline"></i>未作答</div>
											</div>
										</template>
										<div class="knowledge-answer knowledge-score" v-if="answerList.length !=0">
											<span>评分</span>
											<el-input-number class="i_grade" @change="setScore($event, list, item)" placeholder="请输入评分" v-model="answerList[item.id].score" controls-position="right" :controls='false' :min="0" :max="item.score">
											</el-input-number>
										</div>
										<div class="knowledge-answer" v-if="answerList.length !=0">
											<span>评语</span>
											<!-- <div class="knowledge-html" v-html="answerList[item.id].comment"></div> -->
											<Ueditor v-model="answerList[item.id].comment" :writeMsg="answerList[item.id].comment" :id="'ueditor1'+(index+1)" :config="config1" :ref="'option'+(index+1)"></Ueditor>
										</div>
										<el-collapse accordion class="preview-answer">
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>共{{item.score}}分, 得分: {{answerList.length !=0 ? answerList[item.id].score : 0}}</span>
													</div>
												</template>
												<div class="preview-accordion-answer" v-if="0">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>
								</template>
							</ul>
						</li>
					</template>
				</ul>
			</div>
			<div class="exercises-conten-r">
				<div class="exercises-conten-time">
					<div class="exercises-time-countdown">
						<i class="el-icon-time"></i>
						<strong>用时</strong>
						<span>{{testObj.time ? testObj.time : '00:00:00'}}</span>
					</div>
				</div>
				<div class="exercises-rewinding">
					<p>系统改卷</p>
					<ul>
						<li>
							<p>{{answerInfo.count}}</p>
							<p>全部题目</p>
						</li>
						<li>
							<p>{{answerInfo.correct}}</p>
							<p>正确题目</p>
						</li>
						<li>
							<p class="exercises-score">{{answerInfo.score}}</p>
							<p>得分</p>
						</li>
					</ul>
					<p>主观题</p>
					<ul>
						<li>
							<p>{{answerInfo.sum}}</p>
							<p>全部题目</p>
						</li>
						<li>
							<p class="exercises-score">{{answerInfo.score2}}</p>
							<p>得分</p>
						</li>
					</ul>
				</div>
				<ul class="exercises-conten-r-type">
					<template v-for="(type, list) of questionList">
						<li class="exercises-conten-r-type-state exercises-result-state" :key='type.id'>
							<div>{{type.name}}<i>（共{{type.score}}分）</i></div>
							<ul>
								<template v-for="(item, index) of type.children">
									<li v-if="parseInt(item.qt_id) == parseInt(type.id)" :key="item.id">
										<!-- <input type="checkbox" :name="index" :checked="item.html_default"> -->
										<template v-if="answerList.length !=0 && parseInt(item.type_base_id) != 1 && parseInt(item.type_base_id) != 2 &&  parseInt(item.type_base_id) != 4 && answerList[item.id].answer != null">
											<span class="exercises-praise">{{++index}}</span>
										</template>
										<template v-else-if="answerList.length !=0 && parseInt(item.type_base_id) != 1 && parseInt(item.type_base_id) != 2 &&  parseInt(item.type_base_id) != 4 && answerList[item.id].answer == null">
											<span class="exercises-unanswered">{{++index}}</span>
										</template>
										<template v-else>
											<span v-if="item.html_default == 0" class="exercises-unanswered">{{++index}}</span>
											<span v-else-if="item.html_default == 1 " class="exercises-success">{{++index}}</span>
											<span v-else-if="item.html_default == 2" class="exercises-error">{{++index}}</span>
										</template>
									</li>
								</template>
							</ul>
						</li>
					</template>
				</ul>
				<div class="exercises-answer-state">
					<span>正确<i></i></span>
					<span>未答<i></i></span>
					<span>错误<i></i></span>
				</div>
			</div>
		</div>
		<!-- 预览图片 -->
		<image-viewer v-if="imagePreview.showViewer" :initial-index="imageIndex" :on-close="closeViewer" :url-list="imagePreview.previewSrcList">
		</image-viewer>
	</div>
</template>
<script>
import Ueditor from '../base/Ueditor.vue';
export default {
	components: { Ueditor },
	data() {
		return {
			imagePreview: { /*图片预览*/
				showViewer: false,
				previewSrcList: []
			},
			tasksVisible: false,
			headClassList: null,
			type: 1,

			testList: [],
			/* 试卷列表 */
			answerList: [],
			/* 试卷答案 */
			questionList: [],
			/*试卷列表*/
			scoreList: [],
			/*评分*/
			commentList: [],
			/*评语*/
			testObj: {
				name: '',
				time: '',
				time2: '',
				score: 0,
				type: 1,
			},
			totalTimer: 0,
			isPraise: 0,
			/*0.未批，1.已改*/
			recordId: '',
			/*试卷id*/
			answerInfo: {
				count: 0,
				/*系统改卷-全部题目*/
				score: 0,
				/*系统改卷-正确题目*/
				correct: 0,
				/*系统改卷-得分*/
				sum: 0,
				/*主观题--全部题目*/
				score2: 0 /*主观题--得分*/
			},

			loading: true,
			imgIndex: 0,

			customToolbar: [
				[{ list: "ordered" }, { list: "bullet" }],
				[{ 'color': [] }, { 'background': [] }],
				['clean']
			],

			config1: {
				zIndex: 3,
				textIndent: 0,
				maximumWords: 2000,
				elementPathEnabled: false,
				/*元素路径*/
				enableAutoSave: false,
				autoHeightEnabled: false,
				autoFloatEnabled: false, //不允许滚动时固定在顶部
				initialContent: '请输入内容...', //初始化编辑器的内容,也可以通过textarea/script给值，看官网例子
				autoClearinitialContent: true, //是否自动清除编辑器初始内容，注意：如果focus属性设置为true,这个也为真，那么编辑器一上来就会触发导致初始化的内容看不到了
				initialFrameWidth: null,
				initialFrameHeight: 150,
				serverUrl: this.BASE_URL + "/public/_/UEditor/1.4.3//php/controller.php?action=uploadimage",
				BaseUrl: this.BASE_URL,
				// UEDITOR_HOME_URL: process.env.BASE_URL+'ueditor/',
				UEDITOR_HOME_URL: process.env.BASE_URL ? process.env.BASE_URL + 'ueditor/' : '/public/ueditor/',
				toolbars: [
					['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'pasteplain', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', 'fullscreen', 'simpleupload', 'link', 'justifyleft', 'justifyright', 'justifycenter', 'lineheight', 'fontfamily', 'fontsize', 'undo', 'redo']
				]
			},
			data: {
				userid: this.$g.user_id,
				record_id: this.recordId,
				question_id: this.$route.query.tid,
				score: undefined,
				comment: undefined,
				type: undefined,
				mark_status: undefined
			}

		}
	},
	mounted() {
		this.headClassList = document.querySelector('#reception').classList;
		this.headClassList.add('hidden-header')


		document.addEventListener('click', (e) => {

			let [targetSrc, imgs, srcArr, currentIdx] = ['', '', '', '']
			if (e.target.nodeName === 'IMG') {

				this.imagePreview.showViewer = true
				targetSrc = e.target.src;
				imgs = [...e.target.parentNode.children];
				srcArr = imgs.map(item => item.currentSrc);
				currentIdx = srcArr.indexOf(targetSrc);

				this.imagePreview.previewSrcList = srcArr
				this.imgIndex = targetSrc

			}

		}, false)
	},
	computed: {
		imageIndex() {
			return this.imagePreview.previewSrcList.indexOf(this.imgIndex);
		}

	},
	destroyed() {
		this.headClassList.remove('hidden-header')
	},
	created() {
		this.getTestList()
	},
	methods: {
		/**
		 * 关闭图片
		 * @DateTime 2020-04-16T17:40:41+0800
		 * @qiu_m
		 * @return   {[type]}                 [description]
		 */
		closeViewer() {
			this.imagePreview.showViewer = false;
			this.imagePreview.previewSrcList = []
		},
		markStatus(status = false) {
			let [scoreArr, commentArr] = [
				[],
				[]
			]
			this.answerList.forEach(item => {
				if ([3,5].includes(item.type)) {
					scoreArr.push({ id: item.id, score: item.score });
					commentArr.push({ id: item.id, comment: item.comment })
				}
			})

			let success = (res => {
				this.$message.success(res.msg);
				status && this.$router.back(-1)
			});


			this.data.record_id = this.recordId,
			this.data.score = scoreArr
			this.data.comment = commentArr
		
			/*提交并告知学生*/
			if (status) {
				this.data.mark_status = 1
				this.data.type = 1
			}else{/*只做保存*/
				this.data.type = undefined
				this.data.mark_status = 0
			}


			this.$ajax.post('api/task/review_test', this.data, { func: { success: success } });
		},
		/*保存试卷*/
		reviewTest() {
			this.$confirm('确认保存阅卷, 是否继续?', '保存阅卷', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'confirm-them',
			}).then(() => {

				this.markStatus()

			}).catch(() => {});
		},
		/*提交试卷*/
		submitTest() {
			this.$confirm('确认保存阅卷, 是否继续?', '保存阅卷', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'confirm-them',
			}).then(() => {

	
				this.markStatus(true)


				// let [scoreArr, commentArr] = [
				// 	[],
				// 	[]
				// ]
				// this.answerList.forEach(item => {

				// 	if (item.type >= 3) {
				// 		scoreArr.push({ id: item.id, score: item.score });
				// 		commentArr.push({ id: item.id, comment: item.comment })
				// 	}
				// })

				// let success = (res => {
				// 	this.$message.success(res.msg);
				// 	this.$router.back(-1)
				// });

				// let params = {
				// 	userid: this.$g.user_id,
				// 	record_id: this.recordId,
				// 	question_id: this.$route.query.tid,
				// 	score: scoreArr,
				// 	comment: commentArr,
				// 	type: 1,
				// 	mark_status: 1
				// };
				// this.$ajax.post('api/task/review_test', params, { func: { success: success } });
			}).catch(() => {});
		},
		/**
		 * fei选择题的评分
		 * @DateTime 2019-08-30T10:13:35+0800
		 * @param    {[type]}                 val [description]
		 * @param    {[type]}                 obj [description]
		 */
		setScore(val, list, obj) {

			this.answerList[obj.id].score = val

			this.answerInfo.score2 = 0;
			this.answerList.forEach(item => {
				if (item.type != 1 && item.type != 2) {

					this.answerInfo.score2 += parseInt(item.score);
				}
			})

		},
		/**
		 * 重新排序试卷
		 * @DateTime 2019-08-12T09:38:37+0800
		 * @param    {[type]}                 arr   [description]
		 * @return   {[type]}                       [description]
		 */
		reSort(arr) {

			return function(a, b) {
				var value1 = a[arr];
				var value2 = b[arr];
				return value1 - value2;
			}
		},
		/**
		 * 根据参数请求试卷详情
		 * @DateTime 2019-07-22T17:37:30+0800
		 * @return   {[type]}                 [description]
		 */
		getTestList() {
			let success = (res => {
				this.testList = res.data.test_detail;
				let data = res.data.test_detail;
				this.testObj.score = 0
				// 计算试卷的总分数
				for (let s = 0; s < this.testList.question_type.length; s++) {
					this.testObj.score += parseInt(this.testList.question_type[s].score)
				};

				/*根据 id 升序排序试卷*/
				this.testList.question_list = this.testList.question_list.sort(this.reSort('qt_id'));

				this.isPraise = res.data.task_record.is_praise;
				this.recordId = res.data.task_record.id
				this.testObj.time = res.data.use_time
				this.renderTimeuse(this.testObj.time)
				this.testObj.name = res.data.task_name;
				this.totalTimer = res.data.length;

				let [indexs, scoreSum, correctIndex, keys, scoreSum2] = [0, 0, 0, 0, 0]
				/* 获取作答者的作答答案 */
				res.data.task_record.task_record_detail.forEach(item => {

					if ([1,2,3,4].includes(item.qt_base_id) ) {
						item.answer = JSON.parse(item.answer) ? JSON.parse(item.answer) : []
					} else {
						item.answer = item.answer != '[""]' ? JSON.parse(item.answer) : ''

					}

					/*答案*/
					this.answerList[item.question_id] = {
						type: item.qt_base_id,
						id: item.question_id,
						score: item.score,
						answer: item.answer,
						comment: item.teacher_comment
					}


					/* 系统改卷 */
					if ([1,2,4].includes(item.qt_base_id) ) {
						scoreSum += parseInt(item.score)
							++indexs
						if (parseInt(item.score) > 0) {++correctIndex }
					} else {
						++keys
						if (this.isPraise == 0) {
							scoreSum2 += parseInt(item.score)
						} else {
							scoreSum2 += parseInt(item.score)
						}
					}

				});

				this.answerInfo.count = indexs;
				this.answerInfo.score = scoreSum;
				this.answerInfo.correct = correctIndex;
				this.answerInfo.sum = keys;
				// this.answerInfo.score2 = scoreSum2;


				/*组装一个新的试卷数据*/
				this.questionList = [];
				data.question_type.forEach((item) => {
					this.questionList.push({
						id: item.id,
						count: item.count,
						name: item.question_type,
						score: item.score,
						type: item.cn_num,
						children: []
					});
				})

				data.question_list.forEach((list, key) => {

					/*遍历试题*/
					this.questionList.forEach((item, index) => {
						if (list.qt_id == item.id) {
							item.children.push(list)

						}
					});
					if (this.answerList.length == 0) { return }
					/*是否选择题*/
					if ([1,2,4].includes(list.type_base_id)) {
						
						if (this.answerList[list.id].score != 0) {
							list.html_default = 1 /*正确*/
						} else if (this.answerList[list.id].answer.length == 0) {
							list.html_default = 0 /*未答*/
						} else {
							list.html_default = 2 /*错误*/
						}


					} else { /*非选择题*/
						if (this.isPraise == 1) {
							if (this.answerList[list.id].score != 0) {
								list.html_default = 1 /*正确*/
							} else if (this.answerList[list.id].answer == '' || this.answerList[list.id].answer == null) {
								list.html_default = 0 /*未答*/
							} else {
								list.html_default = 2 /*错误*/
							}
						} else {
							if (this.answerList[list.id].answer == '' || this.answerList[list.id].answer == null) {
								list.html_default = 0 /*未答*/
							}
						}
					}
				});



				this.loading = false
				// answerList[item.id].score != 0
			});

			let params = {
				userid: this.$route.query.uid,
				task_id: this.$route.query.tid,
				classid: this.$route.query.id
			};

			let fail = (res => {
				this.$message.error({
					duration: 8000,
					message: res.msg
				})
			})

			this.$ajax({
				url: 'api/task/resource_by_taskid',
				method: 'get',
				params: params,
				func: { success: success, fail: fail }
			})
		},
		renderTimeuse(time) {
			var t = parseInt(time * 1000)
			if (t > 0) {
				let day = Math.floor(t / 86400000);
				let hour = Math.floor((t / 3600000) % 24);
				let min = Math.floor((t / 60000) % 60);
				let sec = Math.floor((t / 1000) % 60);
				hour = hour < 10 ? "0" + hour : hour;
				min = min < 10 ? "0" + min : min;
				sec = sec < 10 ? "0" + sec : sec;
				let format = '';
				if (day > 0) {
					format = `${day}:${hour}:${min}:${sec}`;
				}
				if (day <= 0 && hour > 0) {
					format = `${hour}:${min}:${sec}`;
				}
				if (day <= 0 && hour <= 0) {
					format = `${hour}:${min}:${sec}`;
				}

				this.testObj.time = format;
			}
		},

		/**
		 * 返回上一页
		 * @return {[type]} [description]
		 */
		goBack() {

			this.$confirm('返回上一页，数据是否要保存”', '提示', {
				confirmButtonText: '保存批阅数据',
				cancelButtonText: '不保存返回',
				type: 'warning',
				customClass: 'confirm-them',
			}).then(() => {
				// this.data.record_id = this.recordId
				// this.data.mark_status = 0
				// this.data.type = undefined
				this.markStatus()
				this.$router.back(-1)

			}).catch(() => {
				this.$router.back(-1)
			});

		},
	}
}
</script>